#!/usr/bin/env python
"""
ChatTTS 快速安装脚本 (跨平台)
支持 Windows/Linux/macOS
"""

import sys
import subprocess
import platform


def run_command(cmd, description):
    """执行命令"""
    print(f"\n{'='*60}")
    print(f"  {description}")
    print(f"{'='*60}\n")
    
    try:
        result = subprocess.run(
            cmd,
            shell=True,
            check=True,
            capture_output=False,
            text=True
        )
        print(f"\n✓ {description} - 成功!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"\n❌ {description} - 失败!")
        print(f"错误: {e}")
        return False


def main():
    """主函数"""
    print("""
╔════════════════════════════════════════╗
║    ChatTTS 自动安装脚本 v1.0          ║
║    完全本地运行的开源TTS引擎           ║
╚════════════════════════════════════════╝
    """)
    
    # 检测操作系统
    os_name = platform.system()
    print(f"检测到操作系统: {os_name}\n")
    
    # 确认安装
    response = input("是否开始安装 ChatTTS? (y/n): ")
    if response.lower() != 'y':
        print("安装已取消")
        return
    
    # 使用国内镜像源
    mirror = "https://pypi.tuna.tsinghua.edu.cn/simple"
    
    # 步骤1: 安装 PyTorch (CPU版本)
    print("\n⏳ 准备安装 PyTorch (这可能需要几分钟)...")
    
    pytorch_cmd = (
        f"pip install torch torchaudio "
        f"--index-url https://download.pytorch.org/whl/cpu "
        f"-i {mirror}"
    )
    
    if not run_command(pytorch_cmd, "安装 PyTorch"):
        print("\n❌ 安装失败! 请检查网络连接或Python环境")
        sys.exit(1)
    
    # 步骤2: 安装 ChatTTS
    print("\n⏳ 准备安装 ChatTTS...")
    
    chattts_cmd = f"pip install ChatTTS omegaconf vocos -i {mirror}"
    
    if not run_command(chattts_cmd, "安装 ChatTTS"):
        print("\n❌ 安装失败!")
        sys.exit(1)
    
    # 步骤3: 验证安装
    print("\n⏳ 验证安装...")
    
    verify_cmd = 'python -c "import ChatTTS; print(\\"✓ ChatTTS 验证成功!\\")"'
    
    if not run_command(verify_cmd, "验证 ChatTTS"):
        print("\n⚠️ 验证失败,但可能已经安装成功")
        print("请尝试运行: python -c \"import ChatTTS\"")
    
    # 完成
    print(f"""
{'='*60}
✅ ChatTTS 安装完成!
{'='*60}

📝 接下来:
1. 首次运行会下载模型文件(约2GB)
2. 下载需要10-20分钟,请耐心等待
3. 启动系统: python main.py
4. 查看文档: ChatTTS本地部署指南.md

💡 提示:
- 模型只需下载一次,之后启动很快
- 可以完全离线使用
- CPU即可运行,有GPU更快

🎤 享受ChatTTS带来的超自然语音吧!
    """)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n安装已中断")
        sys.exit(0)
    except Exception as e:
        print(f"\n\n安装异常: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
